package org.example.backend.Module.System.User.Pojo.Entity;

import cn.hutool.extra.spring.SpringUtil;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.example.backend.Module.System.Role.Pojo.Entity.Role;
import org.example.backend.Module.System.Role.Service.RoleService;
import org.example.backend.Module.System.User.Service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;


@Data
@AllArgsConstructor
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS)
public class MyUserDetails implements UserDetails, Serializable {

    private static RoleService roleService = SpringUtil.getBean(RoleService.class);

    private User user;

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        Role role = MyUserDetails.roleService.getRole(this.user.getRoleId());
        if(role == null) return null;

        List<String> privileges = role.getPrivileges();

        return privileges == null || privileges.isEmpty() ? null :
                privileges.stream().map(s -> (GrantedAuthority) () -> s).collect(Collectors.toList());
    }

    @Override
    public String getPassword() {
        return this.user.getPassword();
    }

    @Override
    public String getUsername() {
        return this.user.getUsername();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return !this.user.getLocked();
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
